#!/usr/bin/python

import re
import sys
import bsddb

LOCUS_RE = re.compile(r"LOCUS\s+(\w+)\s+.*")

def parse_locus(s):
    m = LOCUS_RE.match(s)
    if m:
        return m.groups()[0]
    else:
        return None

if __name__ == "__main__":
 
    db_fname = sys.argv[1]
    input_files_fname = sys.argv[2]

    cnt_all = 0
    cnt_success = 0
    db = bsddb.hashopen(db_fname, 'w')
    for fname in open(input_files_fname):
        cnt_all += 1
        f = open(fname.strip())
        first_line = f.readline()
        locus = parse_locus(first_line)
        if not locus:
            print >> sys.stderr, 'Cannot parse locus from %s' % fname
            continue
        if db.has_key(locus):
            print >> sys.stderr, 'Locus already exists: %s' % locus
            continue
        src = first_line+f.read()
        db[locus] = src
        f.close()
        cnt_success += 1

    db.sync()
    db.close()

    print "Done! (%s/%s)" % (cnt_success, cnt_all)

